package com.server.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author lulei
 * @date 2020年12月25日 12:05:25
 */
public class StaticResourceUtil {
    /**
     * 获取文件绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        absolutePath = absolutePath.replace("\\\\", "/");
        return absolutePath+path;
    }

    /**
     * 传入需要输出静态文件的输入流通过socket的输出流输出
     * @param inputStream
     * @param outputStream
     */
    public  static void  outputStaticResource(InputStream inputStream,OutputStream outputStream) throws IOException {
        int available = 0;
        while (available == 0){
            available = inputStream.available();
        }
        //先输出头纤细
        outputStream.write(HttpProtocolUtil.getHttpStatus200(available).getBytes());
        //正文输出
        //静态资源内容比较大所以需要分段输出
        int written = 0;
        int bytesize = 1024;
        byte[] bt = new byte[bytesize];
        while (written < available){
            if(written + bytesize >available){
                bytesize = available-written;
                bt = new byte[bytesize];
            }
            inputStream.read(bt);
            outputStream.write(bt);
            outputStream.flush();
            written +=bytesize;//计算已经读取的字节长度
        }

    }
}
